﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using System.Text;
using HZ.DrugTrade.Web;

namespace WebDemo.webeditor
{
    public partial class Upload : BasePage
    {
        private static string filetypes = "(doc|jpg|jepg|gif|png|xls|pdf|docx|xlsx)$"; // 允许上传的文件类型

        protected void Page_Load(object sender, EventArgs e)
        {
            // 此处加入身份判断代码
            //if (Session["Account"] == null)
            //{
            //    HZ.Web.MessageBox.Show("登录已过期，请重新登陆再上传");
            //}
        }

        protected void btUpload_Click(object sender, EventArgs e)
        {
            string uploadpath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["UploadPath"]);
            if (fu1.HasFile)
            {
                string filename = fu1.FileName;
                if (CheckExtension(filename))
                {
                    string newfilename = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + HZ.Fun2.GetRandomStr(4) + Path.GetExtension(filename);
                    try
                    {
                        fu1.SaveAs(uploadpath + "\\" + newfilename);
                    }
                    catch
                    {
                        HZ.Web.MessageBox.Show("上传目录无写权限");
                        // code will not run here
                    }
                    string type = "";
                    if (fu1.PostedFile.ContentType.Contains("image"))
                    {
                        type = "img";
                    }
                    else
                    {
                        type = "file";
                    }
                    string tmpRootDir = Server.MapPath(Request.ApplicationPath.ToString());//获取程序根目录
                    string imagesurl2 = (uploadpath + "\\" + newfilename).Replace(tmpRootDir, "/"); //转换成相对路径
                    imagesurl2 = imagesurl2.Replace(@"\", @"/");

                    string fp = Server.UrlEncode(imagesurl2);// string.Format(uploadabpath, newfilename);
                    string url = string.Format("~/webeditor/InsertToEdittor.aspx?url={0}&filename={1}&type={2}", fp, filename, type);
                    Response.Redirect(url, true);
                }
                else
                {

                    HZ.Web.WebUtil.Alert("非法文件类型", this);

                }
            }
            else
            {
                HZ.Web.WebUtil.Alert("请浏览待上传的文件", this);
            }

        }
        private bool CheckExtension(string filename)
        {
            string path = Path.GetExtension(filename);
            return Regex.IsMatch(path, filetypes, RegexOptions.IgnoreCase);
        }
    }
}
